import { useEffect } from "react";

import { ConfigProvider } from "@douyinfe/semi-ui";
import { VChartCore } from "@visactor/react-vchart";
import { useLocalStorageState } from "ahooks";

import { useTranslation } from "react-i18next";
import { defaultLocale } from "@/locale";
import zh_CN from "@douyinfe/semi-ui/lib/es/locale/source/zh_CN";
import en_US from "@douyinfe/semi-ui/lib/es/locale/source/en_US";

import { useRouteProgress } from "@/hooks/useRouteProgress";

import Layout from "./layout/index";
import { GlobalContext } from "./context";
import "./App.css";

function App() {
  useRouteProgress();
  const [lang, setLang] = useLocalStorageState("lang", {
    defaultValue: defaultLocale,
    listenStorageChange: true,
    serializer: (value) => JSON.stringify(value),
    deserializer: (value) => {
      try {
        return JSON.parse(value);
      } catch {
        // 如果解析失败，返回原始值
        return value;
      }
    },
  });

  const [theme, setTheme] = useLocalStorageState("theme", {
    defaultValue: "light",
    listenStorageChange: true,
    serializer: (value) => JSON.stringify(value),
    deserializer: (value) => {
      try {
        return JSON.parse(value);
      } catch {
        // 如果解析失败，返回原始值
        return value;
      }
    },
  });

  const { i18n } = useTranslation();

  useEffect(() => {
    if (theme === "dark") {
      document.body.setAttribute("theme-mode", "dark");
      VChartCore.ThemeManager.setCurrentTheme('legacyDark')
    } else {
      document.body.removeAttribute("theme-mode");
      VChartCore.ThemeManager.setCurrentTheme('legacyLight')
    }
  }, [theme]);
  useEffect(() => {
    i18n.changeLanguage(lang);
  }, [lang, i18n]);

  return (
    <>
      <GlobalContext.Provider value={{ lang, setLang, theme, setTheme }}>
        <ConfigProvider locale={lang === "zh-CN" ? zh_CN : en_US}>
          <Layout></Layout>
        </ConfigProvider>
      </GlobalContext.Provider>
    </>
  );
}
export default App;
